const { Configuration, OpenAIApi } = require("openai");
const express = require("express");

const app = express();

// 初始化 chatgpt 接口
const configuration = new Configuration({
  apiKey: "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", // 官网获取
});

const openai = new OpenAIApi(configuration);

const abortController = new AbortController();
const abortSignal = abortController.signal;

app.get('/chatgpt', async (req, res) => {
  const question = req.query.question;
  // res.writeHead(200, {
  //   'Access-Control-Allow-Origin':'*'//可以是*，也可以是跨域的地址
  // })
  if (!question) {
    res.send({
      message: "The query must contain the question parameter!",
      status: 400
    })
  } else {
    try {
      console.log(question);
      const completion = await openai.createChatCompletion(
        {
          model: 'gpt-3.5-turbo',
          messages: [
            {
              role: 'user',
              content: question,
            },
          ],
          stream: false,
        },
        { responseType: 'json' }
      );
      
      const { role, content } = completion.data.choices[0].message;
      res.setHeader('Access-Control-Allow-Origin', '*' ); // 允许所有跨域网站的响应值
      res.send({
        message: "Get the result of the problem successfully!",
        data: {
          text: content
        },
        status: 200,
      })
    } catch (error) {
      res.setHeader('Access-Control-Allow-Origin', '*' );
      res.send({
        message: "The query must contain the question parameter!",
        status: 200,
        data: {
          text: '抱歉，出错了，请重试一下'
        },
      })
    }
  }
})

app.listen(3000, () => console.log("running..."))